﻿using System;
using System.Threading.Tasks;

using iTool.Cloud.Database.iToolService;
using iTool.Cloud.Database.KeyGeneratorProvider.Contract;
using iTool.Cloud.Database.SyncDatabaseProvider;
using iTool.ClusterComponent;

using Microsoft.Extensions.Options;

using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.Runtime;

namespace iTool.Cloud.Database.ServiceProvider.Implementation
{

    /// <summary>
    /// 以Table 为主题
    /// 每个Service 一个激活
    /// </summary>
    [Reentrant]
    [ClusterPlacementStrategy]
    public class TableVersionService : iToolServiceDataBase, iTableVersionService
    {
        ISyncDatabaseService syncDatabaseService;

        public TableVersionService(KeyGeneratorOptions options, IOptions<ClusterOptions> clusterOptions, ISiloStatusOracle siloStatusOracle) : base(options, clusterOptions, siloStatusOracle)
        {
        }

        public override async Task OnActivateAsync()
        {
            await base.OnActivateAsync();
            this.syncDatabaseService = new SyncDatabaseService(this.TableName, this.SqliteDBVersionConnectionInstanceOfPrivate);
        }

        // 广播条件
        public async Task AcceptNotificationAsync()
        {
            Console.WriteLine("AcceptNotificationAsync:{0}", this.TableName);

            // TODU 开启同步 同步使用本地Service 即可
            this.syncDatabaseService.SyncAsync(this.GrainFactory);
            await Task.CompletedTask;
        }


        public async Task<long> GetCurrentVersionAsync()
        {
            var version = await this.syncDatabaseService.GetCurrentVersionAsync();
            Console.WriteLine("GetCurrentVersionAsync:{0}",version);
            return version;
        }

    }



}
